from multiprocessing.pool import ThreadPool
from threading import Thread
from os.path import exists
from invidious import *
import operator
import time
import sys

from plugins.plugin import Plugin

sys.path.append("..")
from src.video import Video
from src.channel import Channel

from src.utils import *
from src.config import Config
from src.history import History

class InvidiousLastVideos(Plugin):

    def __init__(self, history: History=History(), config: Config=Config()) -> None:
        super().__init__(history, config)

        self.history = history
        self.config = config

        self.name = "[+] Invidious: Last videos"
        self.category = "Invidious"

        self.query_description = """"""

        self.params = {
            'urls' : True
        }

        if exists(self.config.subs_path): self.SUBS_LIST = [i.strip('\n').split(',')[0] for i in open(self.config.subs_path)]
        else: self.SUBS_LIST = []
        self.subscriptions = list()
        self.sorted_sub_videos = list()

        self.flag = "-il"
        self.full_flag = "--ivlastvideos"
        self.flag_help = "show last videos from subscribed channels"
        self.flag_action = "store_true"

    def load_subscription(self, authorId=""):
        chn = self.invidious.get_channel(authorId)
        while chn == None:
            time.sleep(1)
            chn = self.invidious.get_channel(authorId)
        chn.convert(Channel)
        self.subscriptions.append(chn)

    def load_subscriptions(self):
        if len(self.subscriptions) > 0: return
        self.subscriptions.clear()
        self.invidious.update_mirrors()

        pool = ThreadPool(processes=10)
        pool.map(self.load_subscription, self.SUBS_LIST)

        self.subscriptions = sort_channels_by_link_list(self.subscriptions, self.SUBS_LIST)      

    def get_last_videos(self, index: int=0):
        self.load_subscriptions()
        if len(self.sorted_sub_videos) == 0:
            items = []
            for sub in self.subscriptions:
                channel = sub
                latestVideos = channel.latestVideos
                for video in latestVideos:
                    if video == None: continue
                    video.convert(Video)
                    video.url = self.invidious.get_working_mirror() + "/watch?v=" + video.videoId
                    video.isWatched = video.in_history(self.history)
                    items.append(video)

            self.sorted_sub_videos = sorted(items, key=operator.attrgetter('published'), reverse=True)
            for index, item in enumerate(self.sorted_sub_videos):
                self.sorted_sub_videos[index] = item.to_json()

        return self.sorted_sub_videos

    def get_items(self, params):
        return self.get_last_videos()


